﻿using PhotoGallery.Data;
using PhotoGallery.Data.Entity;
using PhotoGallery.Data.Repository;
using PhotoGallery.Infrastructure;
using PhotoGallery.Models.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Web;

namespace PhotoGallery.Models
{
    public class VideoInfo
    {
        public int ID { get; set; }
        [LocalizedDisplayName("title", NameResourceType = typeof(Names))]
        public string Title { get; set; }
        public string FileName { get; set; }
        public string Thumbnail { get; set; }
        [DataType(DataType.MultilineText)]
        [LocalizedDisplayName("description", NameResourceType = typeof(Names))]
        public string Description { get; set; }
        [LocalizedDisplayName("date", NameResourceType = typeof(Names))]
        public DateTime? UploadDate { get; set; }
        
        public string Url { get; set; }
        public string UrlThumbnail { get; set; }
        public string UrlWebm { get; set; }
        public string FileNameWebm { get; set; }
        public string FileNameMp4 { get; set; }
        public string FileNameOgv { get; set; }
        public string FullFileName { get; set; }
        public string FullThumbnailName { get; set; }

        public bool AutoGenerateThumnnails
        {
            get
            {
                return File.Exists(HttpContext.Current.Server.MapPath("~/bin/ffmpeg.exe"));
            }
        }

        public string MimeType
        {
            get
            {
                string ext = Path.GetExtension(FileName).ToLower();
                switch (ext)
                {
                    case ".webm":
                        return "video/webm";
                    case ".ogv":
                        return "video/ogg";
                    default:
                        return "video/mp4";
                }
            }
        }
    }

    public class VideoModel : BaseModel
    {
        string path, url;
        AlbumInfo album;
        private VideoRepository repository;

        //public VideoModel(int albumID)
        //{
        //    //album = new AlbumRepository(Owner).Get(albumID);
        //    path = BasePath + Settings.UploadsFolder + Owner + "\\Videos\\" + getAlbumFolder(album);
        //    url = Settings.UploadsUrl + Owner + "/Videos/" + getAlbumUrl(album);
            
        //    repository = new VideoRepository(albumID, Owner);
        //}

        public VideoModel(AlbumInfo Album)
        {
            album = Album;
            path = BasePath + Settings.UploadsFolder + Owner + "\\Videos\\" + getAlbumFolder(album);
            url = Settings.UploadsUrl + Owner + "/Videos/" + getAlbumUrl(album);

            var albumEntity = AlbumsModel.Convert(album);
            repository = new VideoRepository(albumEntity, Owner);
        }
        public VideoModel(int albumID, string owner, string albumFolder)
        {
            path = BasePath + Settings.UploadsFolder + owner + "\\Videos\\" + albumFolder + "\\";
            url = Settings.UploadsUrl + owner + "/Videos/" + albumFolder + "/";
            
            repository = new VideoRepository(albumID, owner, albumFolder);
        }

        public IEnumerable<VideoInfo> Get()
        {
            List<VideoInfo> videos = new List<VideoInfo>();
            var data = repository.Get();
            foreach (var entity in data)
            {
                var item = new VideoInfo()
                {
                    ID = entity.ID,
                    Title = entity.Title,
                    FileName = entity.FileName,
                    Description = entity.Description,
                    Thumbnail = entity.Thumbnail,

                    Url = url + entity.FileName,
                    UrlThumbnail = url + Path.GetFileNameWithoutExtension(entity.FileName) + ".jpg",
                    FullFileName = path + entity.FileName,
                    FullThumbnailName = path + entity.Thumbnail
                };
                videos.Add(item);
            }
            return videos;
        }

        public VideoInfo Get(int id)
        {
            var entity = repository.Get(id);
            if (entity != null)
            {
                var item = new VideoInfo()
                {
                    ID = entity.ID,
                    Title = entity.Title,
                    Description = entity.Description,
                    FileName = entity.FileName,
                    Thumbnail = entity.Thumbnail,
                    UploadDate = entity.UploadedOn,

                    Url = url + entity.FileName,
                    UrlThumbnail = url + Path.GetFileNameWithoutExtension(entity.FileName) + ".jpg",
                    FullFileName = path + entity.FileName,
                    FullThumbnailName = path + entity.Thumbnail,
                    FileNameMp4 = path + Path.GetFileNameWithoutExtension(entity.FileName) + ".mp4",
                };
                return item;
            }
            return null;
        }

        public VideoInfo GetFirst()
        {
            var entity = repository.GetFirst();
            if (entity != null)
            {
                var item = new VideoInfo()
                {
                    ID = entity.ID,
                    Title = entity.Title,
                    Description = entity.Description,
                    FileName = entity.FileName,
                    Thumbnail = entity.Thumbnail,
                    UploadDate = entity.UploadedOn
                };
                return item;
            }
            return null;
        }


        public IEnumerable<VideoAttacumentsInfo> GetAttachments(int videoID)
        {
            List<VideoAttacumentsInfo> videos = new List<VideoAttacumentsInfo>();
            var data = repository.GetAttachments(videoID);
            foreach (var entity in data)
            {
                var item = new VideoAttacumentsInfo()
                {
                    ID = entity.ID,
                    FileName = entity.FileName,
                    VideoID = entity.VideoID,
                    UploadDate = entity.UploadDate,
                    
                    Url = url + entity.FileName,
                    FullFileName = path + entity.FileName
                };
                videos.Add(item);
            }
            return videos;
        }

        public void Create(VideoInfo video, HttpPostedFileBase file, HttpPostedFileBase thummnail)
        {
            if (file == null || file.FileName == string.Empty)
            {
                return;
            }
            video.FileName = FileUtils.CheckFileExists(file, path);
            file.SaveAs(path + video.FileName);

            if (thummnail != null)
            {
                string tmpThummnailName = file.FileName;
                tmpThummnailName = Path.ChangeExtension(tmpThummnailName, Path.GetExtension(thummnail.FileName));
                video.Thumbnail = FileUtils.CheckFileExists(thummnail, path, tmpThummnailName);
                thummnail.SaveAs(path + video.Thumbnail);
            }


            // Create thumbnail
            if (video.AutoGenerateThumnnails)
            {
                string thumbnail = ThumbCreator.Create(path, video.FileName);
                video.Thumbnail = Path.GetFileName(thumbnail);
                FileHelper.SaveResizedImage(path,video.Thumbnail,video.Thumbnail.Replace("tmp_",""));
                video.Thumbnail = video.Thumbnail.Replace("tmp_", "");
                File.Delete(thumbnail);
                //ThumbCreator.Convert(path, video.FileName);
            }
            else
            {
                if (string.IsNullOrEmpty(video.Thumbnail))
                {
                    video.Thumbnail = "video.jpg";
                }
            }
            var entity = new Video()
            {
                ID = video.ID,
                Title = video.Title,
                Description = video.Description,
                FileName = video.FileName,
                Thumbnail = video.Thumbnail,
                UploadedOn = video.UploadDate
            };
            repository.Create(entity);
        }

        public void Update(VideoInfo video, HttpPostedFileBase file, HttpPostedFileBase file1)
        {
            if (file != null)
            {
                video.FileName = FileUtils.CheckFileExists(file, path);
                file.SaveAs(path + video.FileName);
                // Create thumbnail
                if (video.AutoGenerateThumnnails)
                {
                    string thumbnail = ThumbCreator.Create(path, video.FileName);
                    video.Thumbnail = Path.GetFileName(thumbnail);
                    FileHelper.SaveResizedImage(path, video.Thumbnail, video.Thumbnail.Replace("tmp_", ""));
                    video.Thumbnail = video.Thumbnail.Replace("tmp_", "");
                    File.Delete(thumbnail);
                    //ThumbCreator.Convert(path, video.FileName);
                }
                else
                {
                    if (string.IsNullOrEmpty(video.Thumbnail))
                    {
                        video.Thumbnail = "video.jpg";
                    }
                }
            }
            
            var entity = new Video()
            {
                ID = video.ID,
                Title = video.Title,
                Description = video.Description,
                FileName = video.FileName,
                Thumbnail = video.Thumbnail,
                UploadedOn = video.UploadDate
            };
            repository.Update(entity);
            // TODO -----------------------------------------------------------------------------------
            if (file1 != null)
            {
                string fName = FileUtils.CheckFileExists(file1, path);
                var e = new VideoAttachments()
                {
                    //ID = video.ID,
                    FileName = fName,
                    UploadDate = video.UploadDate,
                    VideoID = video.ID

                };
                VideoAttachmentsRepository repo = new VideoAttachmentsRepository(album.ID, video.ID, Owner);
                repo.Create(e);
            }
            // TODO -----------------------------------------------------------------------------------
        }

        public void Delete(VideoInfo video)
        {
            var entity = new Video()
            {
                ID = video.ID,
                Title = video.Title,
                Description = video.Description,
                FileName = video.FileName,
                Thumbnail = video.Thumbnail,
                UploadedOn = video.UploadDate
            };
            repository.Delete(entity);

        }

        public void Erise(VideoInfo video)
        {
            repository.Erise(video.ID);

            if (video.FileName != string.Empty && System.IO.File.Exists(path + video.FileName))
            {
                System.IO.File.Delete(path + video.FileName);
            }
            if (video.Thumbnail != string.Empty && System.IO.File.Exists(path + video.Thumbnail))
            {
                System.IO.File.Delete(path + video.Thumbnail);
            }
        }
    }
}